<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
  <th:block th:include="include :: header('任务实例')" />
  <th:block th:include="include :: select2-css" />
</head>
<body class="gray-bg">

<div class="container-div">
  <div class="row">
    <div class="col-sm-12 search-collapse">
      <form id="tree-form">
        <input type="hidden" name="resetSearch" value="false" />
        <div class="select-list">
          <ul>
            <li>
              <label>Job：</label>
              <select class="form-control" name="jobId">
                <option value=""></option>
              </select>
            </li>
            <li>
              <label>InstanceId：</label>
              <input type="text" name="instanceId" autocomplete="off" />
            </li>
            <li>
              <label>运行状态：</label>
              <select class="form-control" name="runState" th:with="enum=${@disjobService.enums('RunState')}">
                <option value="" selected>所有</option>
                <option th:each="e : ${enum}" th:text="${e.desc}" th:value="${e.value}"></option>
              </select>
            </li>
            <li>
              <label>运行类型：</label>
              <select class="form-control" name="runType" th:with="enum=${@disjobService.enums('RunType')}">
                <option value="" selected>所有</option>
                <option th:each="e : ${enum}" th:text="${e.desc}" th:value="${e.value}"></option>
              </select>
            </li>
            <li class="select-time">
              <label>触发时间：</label>
              <input name="startTime" type="text" id="tree-startTime" autocomplete="off" />
              <span>~</span>
              <input name="endTime" type="text" id="tree-endTime" autocomplete="off" />
            </li>
            <li>
              <a class="btn btn-primary btn-rounded btn-sm" onclick="$.treeTable.search('tree-form', 'tree-table')"><i class="fa fa-search"></i>&nbsp;搜索</a>
              <a class="btn btn-warning btn-rounded btn-sm" onclick="resetForm('tree-form', 'tree-table')"><i class="fa fa-refresh"></i>&nbsp;重置</a>
            </li>
          </ul>
        </div>
      </form>
    </div>
    <div class="btn-group-sm" id="tree-toolbar" role="group">
    </div>
    <div class="col-sm-12 select-table table-striped">
      <table id="tree-table"></table>
    </div>
  </div>
</div>

<div class="container-div">
  <div class="row">
    <div class="col-sm-12 search-collapse">
      <form id="flat-form">
        <input type="hidden" name="resetSearch" value="false" />
        <div class="select-list">
          <ul>
            <li>
              <label>Job：</label>
              <select class="form-control" name="jobId">
                <option value=""></option>
              </select>
            </li>
            <li>
              <label>InstanceId：</label>
              <input type="text" name="instanceId" autocomplete="off" />
            </li>
            <li>
              <label>运行状态：</label>
              <select class="form-control" name="runState" th:with="enum=${@disjobService.enums('RunState')}">
                <option value="" selected>所有</option>
                <option th:each="e : ${enum}" th:text="${e.desc}" th:value="${e.value}"></option>
              </select>
            </li>
            <li>
              <label>运行类型：</label>
              <select class="form-control" name="runType" th:with="enum=${@disjobService.enums('RunType')}">
                <option value="" selected>所有</option>
                <option th:each="e : ${enum}" th:text="${e.desc}" th:value="${e.value}"></option>
              </select>
            </li>
            <li class="select-time">
              <label>触发时间：</label>
              <input name="startTime" type="text" id="flat-startTime" autocomplete="off" />
              <span>~</span>
              <input name="endTime" type="text" id="flat-endTime" autocomplete="off" />
            </li>
            <li>
              <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search('flat-form', 'flat-table')"><i class="fa fa-search"></i>&nbsp;搜索</a>
              <a class="btn btn-warning btn-rounded btn-sm" onclick="resetForm('flat-form', 'flat-table')"><i class="fa fa-refresh"></i>&nbsp;重置</a>
            </li>
          </ul>
        </div>
      </form>
    </div>
    <div class="btn-group-sm" id="flat-toolbar" role="group">
    </div>
    <div class="col-sm-12 select-table table-striped">
      <table id="flat-table"></table>
    </div>
  </div>
</div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: bootstrap-table-fixed-columns-js" />
<th:block th:include="include :: select2-js" />

<script th:inline="javascript">
  const operateFlag = [[${@permission.hasPermi('disjob:instance:operate')}]];
  const runTypes = [[${@disjobService.enums('RunType')}]];
  const runStates = [[${@disjobService.enums('RunState')}]];
  const prefix = ctx + "disjob/instance";
  const stateMap = {10: "info", 20: "success", 30: "warning", 40: "primary", 50: "danger"};

  const defaultOps = {
    uniqueId: "instanceId",
    expandAll: false,
    expandFirst: false,
    showToggle: false,
    expandColumn: 1,
    pagination: true,
    viewUrl: prefix + "/tasks/{id}",
    modalName: "任务实例",
    fixedColumns: true,
    fixedNumber: 2,
    onLoadSuccess: function () {
      $("input[name='resetSearch']").val("false");
    },
    columns: [{
      field: 'selectItem',
      radio: true
    },
    {
      field: 'instanceId',
      title: 'InstanceId',
      width: '240',
      formatter: function (value, row, index) {
        return value === row.wnstanceId ? value : '<a href="javascript:void(0)" onclick="$.operate.view(\'' + value + '\')">' + value + '</a>';
      }
    },
    {
      field: 'jobId',
      title: 'JobId',
      width: '150',
      formatter: function (value, row, index) {
        return '<a href="javascript:void(0)" onclick="job(\'' + value + '\')">' + value + '</a>';
      }
    },
    {
      field: 'runState',
      title: '运行状态',
      width: '70',
      formatter: function (value, row, index) {
        if (row.retrying) {
          return $.common.sprintf("<span class='badge badge-%s'>%s</span>", "success", "重试中");
        }
        const label = $.table.selectData(runStates, value, 'value', 'desc');
        return $.common.sprintf("<span class='badge badge-%s'>%s</span>", stateMap[value], label);
      }
    },
    {
      field: 'runType',
      title: '运行类型',
      width: '70',
      formatter: function (value, row, index) {
        return $.table.selectData(runTypes, value, 'value', 'desc');
      }
    },
    {
      field: 'triggerTime',
      title: '计划触发时间',
      width: '140',
      formatter: function (value, row, index) {
        return $.common.dateFormat(parseInt(value), 'yyyy-MM-dd HH:mm:ss');
      }
    },
    {
      field: 'runStartTime',
      title: '运行开始时间',
      width: '140'
    },
    {
      field: 'runEndTime',
      title: '运行结束时间',
      width: '140',
      visible: false
    },
    {
      field: 'runDuration',
      title: '运行时长',
      width: '90',
      formatter: function (value, row, index) {
        return $.common.formatDuration(value);
      }
    },
    {
      field: 'retriedCount',
      title: '已重试次数',
      width: '85',
      formatter: function (value, row, index) {
        return value === 0 ? "-" : value;
      }
    },
    {
      field: 'workflowCurNode',
      title: '当前节点',
      width: '85',
      formatter: function (value, row, index) {
        return $.table.tooltip(value, 20, "open");
      }
    },
    {
      field: 'rnstanceId',
      title: 'RnstanceId',
      width: '150',
      visible: false
    },
    {
      field: 'pnstanceId',
      title: 'PnstanceId',
      width: '150',
      visible: false
    },
    {
      field: 'wnstanceId',
      title: 'WnstanceId',
      width: '150',
      visible: false
    },
    {
      title: '操作',
      align: 'center',
      formatter: function (value, row, index) {
        if (row.wnstanceId && row.wnstanceId !== row.instanceId) {
          // return '<a style="pointer-events:none;" href="javascript:;" class="btn btn-default btn-rounded btn-xs disabled"><i class="fa fa-chevron-circle-right"></i> 操作</a>';
          return '<button disabled class="btn btn-default btn-rounded btn-xs disabled" data-toggle="tooltip" data-placement="left" title="工作流请操作主实例"><i class="fa fa-chevron-circle-right"></i> 操作</button>';
        }
        if (row.retrying) {
          return '<button disabled class="btn btn-default btn-rounded btn-xs disabled" data-toggle="tooltip" data-placement="left" title="重试中请操作子实例"><i class="fa fa-chevron-circle-right"></i> 操作</button>';
        }
        if (row.runType === 3 && row.runState >= 40) {
          return '<button disabled class="btn btn-default btn-rounded btn-xs disabled" data-toggle="tooltip" data-placement="left" title="删除操作在父实例上"><i class="fa fa-chevron-circle-right"></i> 操作</button>';
        }

        const actions = [];
        if (row.runState <= 20) {
          actions.push("<a class='btn btn-warning btn-rounded btn-xs " + operateFlag + "' href='javascript:void(0)' onclick='operate(&quot;" + row.instanceId + "&quot;, &quot;pause&quot;, &quot;暂停&quot;)'><i class='fa fa-pause'></i> 暂停</a> ");
        }
        if (row.runState === 30) {
          actions.push("<a class='btn btn-info btn-rounded btn-xs " + operateFlag + "' href='javascript:void(0)' onclick='operate(&quot;" + row.instanceId + "&quot;, &quot;resume&quot;, &quot;恢复&quot;)'><i class='fa fa-play'></i> 恢复</a> ");
        }
        if (row.runState < 40) {
          actions.push("<a class='btn btn-danger btn-rounded btn-xs " + operateFlag + "' href='javascript:void(0)' onclick='operate(&quot;" + row.instanceId + "&quot;, &quot;cancel&quot;, &quot;取消&quot;)'><i class='fa fa-remove'></i> 取消</a> ");
        }
        if (row.runState >= 40) {
          actions.push("<a class='btn btn-danger btn-rounded btn-xs " + operateFlag + "' href='javascript:void(0)' onclick='operate(&quot;" + row.instanceId + "&quot;, &quot;remove&quot;, &quot;删除&quot;)'><i class='fa fa-trash'></i> 删除</a> ");
        }
        return '<a tabindex="0" class="btn btn-info btn-rounded btn-xs" role="button" data-container="body" data-placement="left" data-toggle="popover" data-html="true" data-trigger="hover" data-content="' + actions.join('') + '"><i class="fa fa-chevron-circle-right"></i> 操作</a>';
      }
    }]
  };

  $(function () {
    const treeOps = $.extend({
      id: "tree-table",
      formId: "tree-form",
      toolbar: "tree-toolbar",
      code: "instanceId",
      parentCode: "pnstanceId",
      url: prefix + "/tree",
      dataUrl: prefix + "/children",
      firstLoad: false
    }, defaultOps);
    $.treeTable.init(treeOps);

    const flatOps = $.extend({
      id: "flat-table",
      formId: "flat-form",
      toolbar: "flat-toolbar",
      url: prefix + "/flat",
      firstLoad: false
    }, defaultOps);
    $.table.init(flatOps);

    layui.use('laydate', function () {
      let treeStartDate = layui.laydate.render({
        elem: '#tree-startTime',
        type: 'datetime',
        max: $('#tree-endTime').val() || '2999-12-31 23:59:59',
        theme: 'molv',
        trigger: 'click',
        done: function (value, date) {
          // 结束时间大于开始时间
          if (value !== '') {
            treeEndDate.config.min.year = date.year;
            treeEndDate.config.min.month = date.month - 1;
            treeEndDate.config.min.date = date.date;
          } else {
            treeEndDate.config.min.year = '';
            treeEndDate.config.min.month = '';
            treeEndDate.config.min.date = '';
          }
        }
      });
      let treeEndDate = layui.laydate.render({
        elem: '#tree-endTime',
        type: 'datetime',
        min: $('#tree-startTime').val() || '1900-01-01 00:00:00',
        theme: 'molv',
        trigger: 'click',
        done: function (value, date) {
          // 开始时间小于结束时间
          if (value !== '') {
            treeStartDate.config.max.year = date.year;
            treeStartDate.config.max.month = date.month - 1;
            treeStartDate.config.max.date = date.date;
          } else {
            treeStartDate.config.max.year = '';
            treeStartDate.config.max.month = '';
            treeStartDate.config.max.date = '';
          }
        }
      });
      let flatStartDate = layui.laydate.render({
        elem: '#flat-startTime',
        type: 'datetime',
        max: $('#flat-endTime').val() || '2999-12-31 23:59:59',
        theme: 'molv',
        trigger: 'click',
        done: function (value, date) {
          // 结束时间大于开始时间
          if (value !== '') {
            flatEndDate.config.min.year = date.year;
            flatEndDate.config.min.month = date.month - 1;
            flatEndDate.config.min.date = date.date;
          } else {
            flatEndDate.config.min.year = '';
            flatEndDate.config.min.month = '';
            flatEndDate.config.min.date = '';
          }
        }
      });
      let flatEndDate = layui.laydate.render({
        elem: '#flat-endTime',
        type: 'datetime',
        min: $('#flat-startTime').val() || '1900-01-01 00:00:00',
        theme: 'molv',
        trigger: 'click',
        done: function (value, date) {
          // 开始时间小于结束时间
          if (value !== '') {
            flatStartDate.config.max.year = date.year;
            flatStartDate.config.max.month = date.month - 1;
            flatStartDate.config.max.date = date.date;
          } else {
            flatStartDate.config.max.year = '';
            flatStartDate.config.max.month = '';
            flatStartDate.config.max.date = '';
          }
        }
      });
    });

    // ---------------------------------select2
    $("select[name='jobId']").select2({
      ajax: {
        url: prefix + "/job/search",
        type: "get",
        dataType: 'json',
        delay: 600,
        cache: true,
        data: function (params) {
          return {"term": params.term};
        },
        processResults: function (resp) {
          return {results: resp.data };
        }
      },
      placeholder: "`name`或`group: name`搜索",
      minimumInputLength: 1,
      templateSelection: function (repo) {
        const array = repo.text.split(" | ");
        return array.length > 1 ? array[1] : array[0];
      },
      width: "resolve"
    });

  });

  function resetForm(formId, tableId) {
    const formElem = $("#" + formId);
    formElem.find("input[name='resetSearch']").val("");
    $.form.reset(formId, tableId);
    ["jobId", "runState", "runType"].forEach(function (item) {
      const elem = formElem.find("select[name='" + item + "']");
      elem.val(elem.val()).trigger("change");
    });
  }

  function job(jobId) {
    const url = ctx + 'disjob/job/detail/' + jobId;
    $.modal.open("作业配置详情", url, null, null, null, ['关闭']);
  }

  function operate(instanceId, type, message) {
    table.set();
    $.modal.confirm("确认要" + message + "吗？", function () {
      $.operate.post(prefix + "/" + type + "/" + instanceId);
    });
  }
</script>

</body>
</html>
